/* ==============================================================================
*
*   Copyright (c) 2010, Pierre Favier
*   All rights reserved.
*
*   NTasking is free software: you can redistribute it and/or modify it
*   under the terms of the GNU General Public License as published by the
*   Free Software Foundation.
*
*   Redistribution and use in source and binary forms, with or without
*   modification, are permitted provided that the following conditions
*   are met:
*
*   -   Redistributions of source code must retain the above copyright notice,
*       this list of conditions and the following disclaimer.
*
*   -   Redistributions in binary form must reproduce the above
*       copyright notice, this list of conditions and the following
*       disclaimer in the documentation and/or other materials
*       provided with the distribution.
*
*   THIS SOFTWARE IS PROVIDED "AS IS" AND ANY EXPRESS OR IMPLIED
*   WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
*   OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
*   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
*   BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
*   EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
*   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
*   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
*   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
*   TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
*   THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
*   SUCH DAMAGE.
*
* ============================================================================== */

using System;
using System.Threading;
using NUnit.Framework;
using Rhino.Mocks;
using Rhino.Mocks.Constraints;

namespace NTasking.ValidationTests.Other.SyntaxErrors
{

    [TestFixture]
    public class SynchronizedObjects : ValidationTest
    {

        internal class CountProtected : Protected
        {
            [Entry]
            internal Action AnEntry { get; private set; }


            [Entry]
            internal ActionFamily<int> AFamily { get; private set; }


            [ReadWriteOperation]
            internal Action AnRWOperation { get; private set; }


            [ReadOnlyOperation]
            internal Func<bool> AnROOperation { get; private set; }


            internal CountProtected()
            {
                Entry(AnEntry, When: () => true, Is: () => { });

                Entry(AFamily, When: (i) => true, Is: (i) => { });

                ReadWriteOperation(AnRWOperation, Is: () => { });

                ReadOnlyOperation(AnROOperation, Is: () =>
                {
                    AnRWOperation();
                    return true;
                });
            }

        }


        internal class CountTask : Task
        {
            [Entry]
            internal Action AnEntry { get; private set; }


            [Entry]
            internal ActionFamily<int> AFamily { get; private set; }


            internal CountTask()
                : base()
            { }


            protected override void Body()
            {
            }

        }


        [Test]
        public void Count()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();
            CountProtected prot = null;
            CountTask task = null;

            Ada.Declare(() =>
            {
                prot = new CountProtected();
                task = new CountTask();

                // Setup text expectations

                Expect.Call(result.TestFailed).Repeat.Never();

                Mocks.ReplayAll();
            },
            Begin: () =>
            {
                try
                {
                    Action anAction = null;

                    anAction.Count();
                    // Exception not thrown
                    result.TestFailed();
                }
                catch (SyntaxError ex)
                {
                    if (ex.ErrorCode != Errors.EntryIsNullError)
                        // Wrong error code
                        result.TestFailed();
                }
                catch (Exception)
                {
                    // Wrong exception thrown
                    result.TestFailed();
                }

                try
                {
                    Action anAction = delegate { };

                    anAction.Count();
                    // Exception not thrown
                    result.TestFailed();
                }
                catch (SyntaxError ex)
                {
                    if (ex.ErrorCode != Errors.NotASynchronizedMethodError)
                        // Wrong error code
                        result.TestFailed();
                }
                catch (Exception)
                {
                    // Wrong exception thrown
                    result.TestFailed();
                }

                try
                {
                    prot.AnROOperation.Count();
                    // Exception not thrown
                    result.TestFailed();
                }
                catch (SyntaxError ex)
                {
                    if (ex.ErrorCode != Errors.NotAnEntryError)
                        // Wrong error code
                        result.TestFailed();
                }
                catch (Exception)
                {
                    // Wrong exception thrown
                    result.TestFailed();
                }

                try
                {
                    prot.AnRWOperation.Count();
                    // Exception not thrown
                    result.TestFailed();
                }
                catch (SyntaxError ex)
                {
                    if (ex.ErrorCode != Errors.NotAnEntryError)
                        // Wrong error code
                        result.TestFailed();
                }
                catch (Exception)
                {
                    // Wrong exception thrown
                    result.TestFailed();
                }

                try
                {
                    prot.AnEntry.Count();
                }
                catch (Exception)
                {
                    // Exception thrown
                    result.TestFailed();
                }

                try
                {
                    prot.AFamily[1].Count();
                }
                catch (Exception)
                {
                    // Exception thrown
                    result.TestFailed();
                }

                try
                {
                    task.AnEntry.Count();
                }
                catch (Exception)
                {
                    // Exception thrown
                    result.TestFailed();
                }

                try
                {
                    task.AFamily[1].Count();
                }
                catch (Exception)
                {
                    // Exception thrown
                    result.TestFailed();
                }
            },
            Exception: (ex) =>
            {
                // Unexpected exception thrown
                result.TestFailed();

                return false;
            });
        }


        internal class RequeueProtected : ValidationTestProtected
        {
            [Entry]
            internal Action AnEntry { get; private set; }


            [Entry]
            internal ActionFamily<int> AFamily { get; private set; }


            [ReadWriteOperation]
            internal Action AnRWOperation { get; private set; }


            [ReadOnlyOperation]
            internal Func<bool> AnROOperation { get; private set; }


            internal RequeueProtected(IValidationTestResult result)
                : base (result)
            {
                Entry(AnEntry, When: () => true, Is: () => { });

                Entry(AFamily, When: (i) => true, Is: (i) => { });

                ReadWriteOperation(AnRWOperation, Is: () => { });

                ReadOnlyOperation(AnROOperation, Is: () =>
                {
                    AnRWOperation();
                    return true;
                });
            }

        }


        internal class RequeueTask : ValidationTestTask
        {

            [Entry]
            internal Action AnEntry { get; private set; }


            [Entry]
            internal ActionFamily<int> AFamily { get; private set; }


            private RequeueProtected _prot;


            internal RequeueTask(IValidationTestResult result, RequeueProtected prot)
                : base(result)
            {
                _prot = prot;
            }


            protected override void Body()
            {
                Accept(AnEntry, () =>
                {
                    try
                    {
                        Action anEntry = null;
                        Requeue(anEntry);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (SyntaxError ex)
                    {
                        if (ex.ErrorCode != Errors.RequeueTargetIsNullError)
                            // Wrong error code
                            Result.TestFailed();
                    }
                    catch (Exception)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                    try
                    {
                        Action anEntry = delegate {};
                        Requeue(anEntry);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (SyntaxError ex)
                    {
                        if (ex.ErrorCode != Errors.RequeueTargetIsNotSynchronizedError)
                            // Wrong error code
                            Result.TestFailed();
                    }
                    catch (Exception)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                    try
                    {
                        Requeue(_prot.AnROOperation);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (SyntaxError ex)
                    {
                        if (ex.ErrorCode != Errors.RequeueTargetIsNotAnEntryError)
                            // Wrong error code
                            Result.TestFailed();
                    }
                    catch (Exception)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                    try
                    {
                        Requeue(_prot.AnRWOperation);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (SyntaxError ex)
                    {
                        if (ex.ErrorCode != Errors.RequeueTargetIsNotAnEntryError)
                            // Wrong error code
                            Result.TestFailed();
                    }
                    catch (Exception)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                    try
                    {
                        Requeue(AnEntry);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (SyntaxError ex)
                    {
                        if (ex.ErrorCode != Errors.RequeueOnSameEntryError)
                            // Wrong error code
                            Result.TestFailed();
                    }
                    catch (Exception)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                    try
                    {
                        Requeue(AFamily[1]);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (ThreadAbortException)
                    {}
                    catch (Exception ex)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                });

                Accept(AFamily, (i) =>
                {
                    try
                    {
                        Requeue(AFamily[1]);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (SyntaxError ex)
                    {
                        if (ex.ErrorCode != Errors.RequeueOnSameEntryError)
                            // Wrong error code
                            Result.TestFailed();
                    }
                    catch (Exception ex)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }

                    try
                    {
                        Requeue(AFamily[2]);
                        // Requeue not performed
                        Result.TestFailed();
                    }
                    catch (ThreadAbortException)
                    { }
                    catch (Exception ex)
                    {
                        // Wrong exception
                        Result.TestFailed();
                    }
                });

                Accept(AFamily, (i) =>
                {             
                });

                try
                {
                    Requeue(AFamily[1]);
                    // Requeue not performed
                    Result.TestFailed();
                }
                catch (SyntaxError ex)
                {
                    if (ex.ErrorCode != Errors.RequeueWhenNotInEntryError)
                        // Wrong error code
                        Result.TestFailed();
                }
                catch (Exception)
                {
                    // Wrong exception
                    Result.TestFailed();
                }
            }

        }


        [Test]
        public void Requeue()
        {
            IValidationTestResult result = Mocks.DynamicMock<IValidationTestResult>();
            RequeueProtected prot = null;
            RequeueTask task = null;

            Ada.Declare(() =>
            {
                prot = new RequeueProtected(result);
                task = new RequeueTask(result, prot);

                // Setup text expectations

                Expect.Call(result.TestFailed).Repeat.Never();

                Mocks.ReplayAll();
            },
            Begin: () =>
            {
                task.AnEntry();
            },
            Exception: (ex) =>
            {
                // Unexpected exception thrown
                result.TestFailed();

                return false;
            });
        }

    }

}
